#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021-12-2 15:10
# @Author : huabao.tan
# @File : selenium_key.py
# @Software: PyCharm

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.select import Select
from selenium__.logger_ import Log
from time import sleep
import time

getLogger = Log("basepage")
logger = getLogger.get_log()


def open_browser(browser):
    try:
        driver = getattr(webdriver, browser)()

    except Exception as e:
        print(e)
        driver = webdriver.Chrome()
    return driver


class BasePage:

    def __init__(self, browser):
        self.driver = open_browser(browser)
        self.driver.implicitly_wait(0.2)
        self.driver.maximize_window()

    def visit(self, url):
        self.driver.get(url)

    def findElement(self, locator):
        try:
            self.ele = self.driver.find_elements(*locator)
            logger.info("成功定位元素 %s,%s " % (locator[0], locator[1]))
            return self.ele
        except Exception as e:
            logger.error("元素 %s,%s 查找失败, 原因: %s" % (locator[0], locator[1], str(e)))
            return False

    def findElements(self, locator):
        try:
            self.ele = self.driver.find_elements(*locator)
            logger.info("成功定位元素 %s,%s " % (locator[0], locator[1]))
        except Exception as e:
            logger.error("元素 %s,%s 查找失败, 原因: %s" % (locator[0], locator[1], str(e)))
            return False

    def click(self, locator):
        try:
            self.findElement(locator).click()
            logger.info("点击元素(%s,%s) 成功" % (locator[0], locator[1]))
        except Exception as e:
            logger.error("点击元素(%s,%s) 失败， 原因:%s" % (locator[0], locator[1], str(e)))

    def input(self, locator, value):
        self.findElement(locator).send_keys(value)

    def sleep(self, time):
        sleep(time)

    # 判断元素是否存在
    def isElementExit(self, locator):
        try:
            self.driver.find_element(locator)
            return True
        except:
            return False

    def get_ele_text(self, locator):
        texts = []
        isEle = self.isElementExit(locator)
        if isEle:
            self.ele = self.findElement(locator)
            for i in self.ele:
                texts.append(i.text)
            logger.info("成功从元素 %s 中提取文本内容, 文本为 %s" % (locator, texts))
        return texts


